package 力扣._00周赛._422周赛.问题3;

import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;

class Solution {
    public int minTimeToReach(int[][] moveTime) {
        int n = moveTime.length;
        int m = moveTime[0].length;
        int[][] dp = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                dp[i][j] = Integer.MAX_VALUE;
            }
        }
        dp[0][0] = 0;
        PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[2] - b[2]);
        queue.add(new int[]{0, 0, 0, 0}); // {i, j, time, moveCount}

        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        while (!queue.isEmpty()) {
            int[] current = queue.poll();
            int i = current[0], j = current[1], time = current[2], moveCount = current[3];

            for (int[] dir : directions) {
                int ni = i + dir[0], nj = j + dir[1];
                if (ni >= 0 && ni < n && nj >= 0 && nj < m) {
                    int moveTimeCost = (moveCount % 2 == 0) ? 1 : 2;
                    int newTime = Math.max(time + moveTimeCost, moveTime[ni][nj]+moveTimeCost);
                    if (newTime < dp[ni][nj]) {
                        dp[ni][nj] = newTime;
                        queue.add(new int[]{ni, nj, newTime, moveCount + 1});
                    }
                }
            }
        }

        return dp[n-1][m-1];
    }


}